package cn.cuilan.common.pipeline;

import cn.cuilan.common.entity.HttpEntity;
import cn.cuilan.common.utils.ByteUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.Arrays;

/**
 * 日志处理器
 *
 * @author zhang.yan
 */
@ChannelHandler.Sharable
public class MessageLoggingHandler extends LoggingHandler {

    private final boolean printSensitiveData;
    private final boolean printFieldDescriptions;
    private final int[] maskedFields;

    public MessageLoggingHandler(LogLevel level,
                                 boolean printSensitiveData,
                                 boolean printFieldDescriptions,
                                 int... maskedFields) {
        super(level);
        this.printSensitiveData = printSensitiveData;
        this.printFieldDescriptions = printFieldDescriptions;
        this.maskedFields = maskedFields;
    }

    @Override
    protected String format(ChannelHandlerContext ctx, String eventName, Object obj) {
        if (obj instanceof HttpEntity) {
            return super.format(ctx, eventName, formatHttpEntity((HttpEntity) obj));
        } else {
            return super.format(ctx, eventName, obj);
        }
    }

    private String formatHttpEntity(HttpEntity httpEntity) {
        StringBuilder sb = new StringBuilder();
        sb.append("Length: ").append(ByteUtils.bytesToInt(httpEntity.getLength())).append("\n");
        // 敏感信息
        if (printSensitiveData) {
            sb.append("Message: ").append(Arrays.toString(httpEntity.getMessage()));
        }
        return sb.toString();
    }
}
